import concurrent

from iotdb.Session import Session

from utils.config import Config
from utils.logger import Logger

logger = Logger('Iot').getlogger()


class Iot():
    def __init__(self):
        self.config = Config('../conf/config.ini')
        self.ip = self.config.read_value('iot', 'ip')
        self.port_ = self.config.read_value('iot', 'port')
        self.username_ = self.config.read_value('iot', 'username')
        self.password_ = self.config.read_value('iot', 'password')
        self.session = None  # 初始化session变量

    # 创建一个与IoTDB服务器的会话
    def comm(self):
        if self.session is None:
            self.session = Session(self.ip, self.port_, self.username_, self.password_)
            self.session.open(False)
        return self.session

    # 执行查询语句
    def search(self,query):
        session = self.comm()
        result = session.execute_query_statement(query)
        return result

    # 执行非查询语句
    def non_search(self,query):
        session = self.comm()
        result =session.execute_non_query_statement(query)
        return result

    def concurrent_non_search(self,query):
        session = self.comm()
        # 创建一个线程池，线程数等于 topics_and_payloads 列表的长度
        with concurrent.futures.ThreadPoolExecutor(max_workers=len(query)) as executor:
            # 提交每个 (topic, payload) 对作为任务
            futures = [
                executor.submit(session.execute_non_query_statement,sql)
                for sql in query
            ]
            # 处理每个已完成的任务
            for future in concurrent.futures.as_completed(futures):
                try:
                    future.result()
                except Exception as exc:
                    print(f'Generated an exception: {exc}')
